package city.spring.modules.call.controller;

import city.spring.modules.call.entity.CallRecordEntity;
import city.spring.modules.call.service.CallRecordService;
import city.spring.modules.call.vo.CallRecordVO;
import city.spring.modules.oldman.entity.OldmanInfoEntity;
import city.spring.modules.oldman.service.OldmanInfoService;
import city.spring.utils.BeanUtils;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Controller：呼叫记录表
 *
 * @author 侯坤林
 * @date 2020-09-18 14:28:55
 */
@RestController
@RequestMapping("/call_record")
public class CallRecordController extends ApiController {
    private final CallRecordService callRecordService;
    private final OldmanInfoService oldmanInfoService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<CallRecordEntity, ?>> entityOrderFields;

    public CallRecordController(CallRecordService callRecordService, OldmanInfoService oldmanInfoService) {
        this.callRecordService = callRecordService;
        this.oldmanInfoService = oldmanInfoService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(CallRecordEntity::getId);
        entityOrderFields.add(CallRecordEntity::getOldmanId);
        entityOrderFields.add(CallRecordEntity::getCallTime);
        entityOrderFields.add(CallRecordEntity::getType);
        entityOrderFields.add(CallRecordEntity::getImplementation);
        entityOrderFields.add(CallRecordEntity::getRemarks);
        entityOrderFields.add(CallRecordEntity::getComplete);
        entityOrderFields.add(CallRecordEntity::getGmtCreated);
        entityOrderFields.add(CallRecordEntity::getGmtModified);
    }

    /**
     * 分页获取 <strong>呼叫记录表</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, CallRecordEntity entity) {
        LambdaQueryChainWrapper<CallRecordEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<CallRecordEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        List<CallRecordEntity> records = page.getRecords();
        // 获取该页的所有老人信息对象
        Map<String, OldmanInfoEntity> oldmanInfoEntityMap = oldmanInfoService.listByIds(records, CallRecordEntity::getOldmanId, OldmanInfoEntity::getId);
        OldmanInfoEntity defaultOldmanInfoEntity = new OldmanInfoEntity();
        List<CallRecordEntity> voList = records.stream().map(callRecordEntity -> {
            CallRecordVO vo = BeanUtils.toChildren(callRecordEntity, CallRecordVO.class);
            OldmanInfoEntity oldmanInfoEntity = oldmanInfoEntityMap.getOrDefault(vo.getOldmanId(), defaultOldmanInfoEntity);
            vo.setOldmanName(oldmanInfoEntity.getOldmanName());
            return vo;
        }).collect(Collectors.toList());
        page.setRecords(voList);

        return success(page);
    }

    /**
     * 获取一个 <strong>呼叫记录表</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        CallRecordEntity entity = callRecordService.getById(id);
        CallRecordVO vo = BeanUtils.toChildren(entity, CallRecordVO.class);
        OldmanInfoEntity oldmanInfoEntity = oldmanInfoService.getById(vo.getOldmanId());
        if (oldmanInfoEntity != null) {
            vo.setOldmanName(oldmanInfoEntity.getOldmanName());
        }
        return success(vo);
    }

    /**
     * 添加一个 <strong>呼叫记录表</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody CallRecordEntity entity) {
        callRecordService.saveCallRecord(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>呼叫记录表</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody CallRecordEntity entity) {
        entity.setId(id);
        callRecordService.updateCallRecord(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>呼叫记录表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        callRecordService.deleteCallRecord(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>呼叫记录表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        callRecordService.deleteCallRecord(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<CallRecordEntity> buildLambdaQuery(CallRecordEntity entity) {
        LambdaQueryChainWrapper<CallRecordEntity> lambdaQuery = callRecordService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), CallRecordEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOldmanId()), CallRecordEntity::getOldmanId, entity.getOldmanId());
        lambdaQuery.eq(entity.getCallTime() != null, CallRecordEntity::getCallTime, entity.getCallTime());
        lambdaQuery.eq(entity.getType() != null, CallRecordEntity::getType, entity.getType());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getImplementation()), CallRecordEntity::getImplementation, entity.getImplementation());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRemarks()), CallRecordEntity::getRemarks, entity.getRemarks());
        lambdaQuery.eq(entity.getComplete() != null, CallRecordEntity::getComplete, entity.getComplete());
        lambdaQuery.eq(entity.getGmtCreated() != null, CallRecordEntity::getGmtCreated, entity.getGmtCreated());
        lambdaQuery.eq(entity.getGmtModified() != null, CallRecordEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<CallRecordEntity> buildQuery(CallRecordEntity entity) {
        QueryWrapper<CallRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanId()), "oldman_id", entity.getOldmanId());
        wrapper.eq(entity.getCallTime() != null, "call_time", entity.getCallTime());
        wrapper.eq(entity.getType() != null, "type", entity.getType());
        wrapper.like(StringUtils.isNotBlank(entity.getImplementation()), "implementation", entity.getImplementation());
        wrapper.like(StringUtils.isNotBlank(entity.getRemarks()), "remarks", entity.getRemarks());
        wrapper.eq(entity.getComplete() != null, "complete", entity.getComplete());
        wrapper.eq(entity.getGmtCreated() != null, "gmt_created", entity.getGmtCreated());
        wrapper.eq(entity.getGmtModified() != null, "gmt_modified", entity.getGmtModified());
        return wrapper;
    }

}
